package com.zt.rongda.maintenance.service;

import java.util.List;

import com.zt.rongda.constant.BusConstant;
import com.zt.rongda.maintenance.inter.MaintenanceApplyMapper;
import com.zt.rongda.maintenance.inter.MaintenanceFileMapper;
import com.zt.rongda.maintenance.inter.MaintenanceTaskMapper;
import com.zt.rongda.maintenance.inter.MaintenanceWorkerMapper;
import com.zt.rongda.maintenance.model.MaintenanceApply;
import com.zt.rongda.maintenance.model.MaintenanceFile;
import com.zt.rongda.maintenance.model.MaintenanceTask;
import com.zt.rongda.maintenance.model.MaintenanceWorker;
import com.zt.rongda.util.DesUtils;
import com.zt.rongda.util.JSONUtil;
import com.zt.servlet.FieldAlias;
import com.zt.servlet.FieldAliases;
import com.zt.servlet.Response;
import com.zt.shiro.GlobalInput;
import com.zt.system.model.BusinessException;
import com.zt.servlet.ReqBean;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.system.service.IFieldAliasService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class MaintenanceApplyService extends BaseService implements IFieldAliasService {

    @Autowired
    private MaintenanceApplyMapper maintenanceApplyMapper;

    @Autowired
    private MaintenanceTaskMapper maintenanceTaskMapper;

    @Autowired
    private MaintenanceWorkerMapper maintenanceWorkerMapper;

    @Autowired
    private MaintenanceFileMapper maintenanceFileMapper;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder
                .appendSql("select a.*,c.CUSTOMER_NAME,(SELECT count(1) FROM MAINTENANCE_TASK t "
                        + "where t.`STATUS` = '1' AND t.MAINTENANCE_ID = a.MAINTENANCE_ID) notCompleteTaskCount from MAINTENANCE_APPLY a "
                        + "left join CUSTOMER c on c.CUSTOMER_ID = a.CUSTOMER_ID "
                        + "LEFT JOIN MEDIA_BUS b ON b.BUS_ID = a.MEDIA_ID where 1=1 ");
        sqlBuilder.addWhere("b.VEHICLE_NO", reqBean.getInfo("vehicleNo"))
                .addWhere("a.C_MAINTENANCE_TYPE", reqBean.getInfo("maintenanceType"))
                .addWhere("a.APPLY_COMPANY", reqBean.getInfo("applyCompany"))
                .addWhere("a.CUSTOMER_ID", reqBean.getInfo("customerId"));
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 通过id查询
     * 
     * @param maintenanceId
     * @return
     */
    public MaintenanceApply getById(String maintenanceId) {
        return maintenanceApplyMapper.selectByPrimaryKey(maintenanceId);
    }

    /**
     * 新增
     * 
     * @param maintenanceApply
     */
    public void add(MaintenanceApply maintenanceApply) {
        maintenanceApply.setMaintenanceId(intIncrementId("MAINTENANCE_APPLY", "MAINTENANCE_ID"));// 手动设置Id

        maintenanceApply.setMakeTime(new Date());
        maintenanceApply.setStatus(BusConstant.MaintenanceApply.APPLY_STATUS_TO_DO);
        maintenanceApply.setModifyTime(maintenanceApply.getMakeTime());
        maintenanceApplyMapper.insert(maintenanceApply);
    }

    /**
     * 修改
     * 
     * @param maintenanceApply
     */
    public void update(MaintenanceApply maintenanceApply) {
        String maintenanceId = maintenanceApply.getMaintenanceId();
        if (StringUtil.isEmpty(maintenanceId)) {
            throw new BusinessException("获取主键失败");
        }

        maintenanceApply.setModifyTime(new Date());
        maintenanceApplyMapper.updateByPrimaryKeySelective(maintenanceApply);
    }

    /**
     * 删除
     * 
     * @param maintenanceId
     */
    public void delete(String maintenanceId) {
        if (StringUtil.isEmpty(maintenanceId)) {
            throw new BusinessException("获取主键失败");
        }
        maintenanceApplyMapper.deleteByPrimaryKey(maintenanceId);
    }

    /**
     * 查询最新的车身广告信息
     * 
     * @param reqBean
     * @return
     */
    public JSONObject adDataQuery(ReqBean reqBean) {
        String busId = reqBean.getInfo("busId");
        if (StringUtil.isEmpty(busId)) {
            throw new BusinessException("非法请求!");
        }
        String sql = "SELECT a.BUS_ID,a.VEHICLE_NO,a.VEHICLE_NO_ABBR,a.PLATE_NO,a.LINE_NO,a.COMPANY_NAME,o.CUSTOMER_ID,i.AD_NAME FROM `MEDIA_BUS` a "
                + "LEFT JOIN AD_ORDER_ITEM i ON i.BUS_ID = a.BUS_ID "
                + "LEFT JOIN AD_ORDER o ON o.ORDER_ID = i.ORDER_ID AND o.`STATUS` = ? "
                + "where a.BUS_ID = ? ORDER BY o.FINISH_TIME desc";
        JSONArray array = query(sql, BusConstant.OrderStatus.FINISHED, busId);

        return (array != null && array.size() > 0) ? array.getJSONObject(0) : null;
    }

    /**
     * 客户列表
     * 
     * @param reqBean
     * @return
     */
    public JSONArray customerList(ReqBean reqBean) {
        String sql = "SELECT c.CUSTOMER_ID,c.CUSTOMER_NAME FROM CUSTOMER c";
        return query(sql);
    }

    /**
     * 只查询前五条车辆信息
     * 
     * @param reqBean
     * @return
     */
    public JSONArray queryBus(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from (select a.*,o.CUSTOMER_ID,c.CUSTOMER_NAME,i.AD_NAME,"
                + "i.C_MAKE_TYPE,i.C_PUBLISH_TYPE,i.C_STICKER_TYPE from MEDIA_BUS a "
                + "LEFT JOIN AD_ORDER_ITEM i ON i.BUS_ID = a.BUS_ID "
                + "LEFT JOIN AD_ORDER o ON o.ORDER_ID = i.ORDER_ID AND o.`STATUS` = '"
                + BusConstant.OrderStatus.FINISHED + "'" + "LEFT JOIN CUSTOMER c ON c.CUSTOMER_ID = o.CUSTOMER_ID "
                + "where 1=1 ");
        sqlBuilder.addWhereLike2("a.VEHICLE_NO", reqBean.getInfo("vehicleNo"));
        sqlBuilder.addWhereLike2("a.VEHICLE_NO_ABBR", reqBean.getInfo("vehicleNoAbbr"));
        sqlBuilder.addWhereLike2("a.PLATE_NO", reqBean.getInfo("plateNo"));
        sqlBuilder.orderBy("ORDER BY o.FINISH_TIME desc");
        sqlBuilder.appendSql(") t GROUP BY t.BUS_ID limit 0,5 ");
        return query(sqlBuilder);
    }

    /**
     * 办理
     * 
     * @param reqBean
     */
    public void deal(ReqBean reqBean) {

        String maintenanceId = reqBean.getInfo("maintenanceId");
        boolean showStickerItem = Boolean.parseBoolean(reqBean.getInfo("showStickerItem"));
        String stepListStr = reqBean.getInfo("stepList");
        String publishTaskStr = reqBean.getInfo("publishTask");

        if (StringUtil.isEmpty(maintenanceId) || "{}".equals(publishTaskStr)) {
            throw new BusinessException("非法请求!");
        }

        // 更新申请单的状态和工作流程id
        MaintenanceApply maintenanceApply = maintenanceApplyMapper.selectByPrimaryKey(maintenanceId);
        maintenanceApply.setStatus(BusConstant.MaintenanceApply.APPLY_STATUS_DOING);
        maintenanceApply.setModifyTime(new Date());
        maintenanceApplyMapper.updateByPrimaryKey(maintenanceApply);

        // 插入修补任务
        JSONObject publishTask = JSONObject.fromObject(publishTaskStr);
        MaintenanceTask task = new MaintenanceTask();
        task.setTaskId(intIncrementId("MAINTENANCE_TASK", "TASK_ID"));
        task.setMaintenanceId(maintenanceId);
        task.setTaskType(BusConstant.TaskType.TASK_TYPE_REPAIR);
        task.setStatus(BusConstant.Task.STATUS_NOT_COMPLETE);
        task.setWorkGroupId(publishTask.getString("groupId"));
        task.setStartTime(DateUtil.parseDateTime(publishTask.getString("startTime")));
        task.setLimitTime(DateUtil.parse(publishTask.getString("limitTime")));
        task.setMakeTime(new Date());
        task.setModifyTime(new Date());
        task.setOperator(reqBean.getUserId());
        maintenanceTaskMapper.insert(task);

        // 如果选择了胶贴任务
        if (showStickerItem) {
            if (StringUtil.isEmpty(stepListStr) || "[]".equals(stepListStr)) {
                throw new BusinessException("非法请求!");
            }
            JSONArray stepList = JSONArray.fromObject(stepListStr);
            for (int i = 0; i < stepList.size(); i++) {
                JSONObject json = stepList.getJSONObject(i);
                MaintenanceTask obj = new MaintenanceTask();
                obj.setTaskId(intIncrementId("MAINTENANCE_TASK", "TASK_ID"));
                obj.setMaintenanceId(maintenanceId);
                obj.setTaskType(json.getString("taskType"));
                obj.setStatus(BusConstant.Task.STATUS_NOT_COMPLETE);
                obj.setOwner(json.getString("id"));
                obj.setStartTime(new Date());
                obj.setLimitTime(DateUtil.parse(json.getString("limitTime")));
                obj.setMakeTime(new Date());
                obj.setModifyTime(new Date());
                obj.setOperator(reqBean.getUserId());
                maintenanceTaskMapper.insert(obj);
            }
        }

    }

    /**
     * 查看已处理的申请单 需要查询到已经分配的工作组
     * 
     * @param maintenanceId
     * @return
     */
    @FieldAliases({
            @FieldAlias(service = "maintenanceApplyService", field = "taskId", alias = "workDetails", param = BusConstant.MaintenanceApply.APPLY_QUERY_WORKER),
            @FieldAlias(service = "maintenanceApplyService", field = "taskId", alias = "images", param = BusConstant.MaintenanceApply.APPLY_QUERY_FILE) })
    public JSONArray view(String maintenanceId) {
        if (StringUtils.isEmpty(maintenanceId)) {
            throw new BusinessException("非法请求!");
        }
        String sql = "select t.*,g.GROUP_NAME,e.EMP_NAME FROM MAINTENANCE_TASK t "
                + "LEFT JOIN EMPLOYEE_GROUP g ON g.GROUP_ID = t.WORK_GROUP_ID "
                + "LEFT JOIN EMPLOYEE e ON e.EMP_ID = t.`OWNER` "
                + "where t.MAINTENANCE_ID = ? ORDER BY t.C_TASK_TYPE ASC";
        return query(sql, maintenanceId);
    }

    /**
     * 获取详情
     * 
     * @param fields
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> dealFieldAlias(List<Object> fields, String param) {
        Map<String, Object> map = new HashedMap();
        for (Object field : fields) {
            map.put((String) field, new JSONArray());
        }
        JSONArray array = null;
        SqlBuilder sqlBuilder = null;
        if (BusConstant.MaintenanceApply.APPLY_QUERY_WORKER.equals(param)) {
            sqlBuilder = new SqlBuilder(
                    "SELECT w.TASK_ID,e.EMP_NAME,e.EMP_ID,m.C_LEADER_FLAG FROM MAINTENANCE_WORKER w "
                            + "LEFT JOIN EMPLOYEE e ON e.EMP_ID = w.EMP_ID LEFT JOIN MAINTENANCE_TASK a ON a.TASK_ID = w.TASK_ID "
                            + "LEFT JOIN EMPLOYEE_GROUP_MEMBER m ON m.GROUP_ID = a.WORK_GROUP_ID AND m.EMP_ID = e.EMP_ID "
                            + "where 1=1 ").addWhereIn("w.TASK_ID", fields).orderBy("order by w.MAKE_TIME asc");
        } else if (BusConstant.MaintenanceApply.APPLY_QUERY_FILE.equals(param)) {
            sqlBuilder = new SqlBuilder("SELECT * FROM MAINTENANCE_FILE f where 1=1").addWhereIn("f.TASK_ID", fields);
        } else if (BusConstant.MaintenanceApply.APPLY_QUERY_TASK_DETAILS.equals(param)) {
            sqlBuilder = new SqlBuilder(
                    "SELECT w.TASK_ID,e.EMP_NAME,e.EMP_ID,m.C_LEADER_FLAG FROM MAINTENANCE_WORKER w "
                            + "LEFT JOIN EMPLOYEE e ON e.EMP_ID = w.EMP_ID LEFT JOIN MAINTENANCE_TASK a ON a.TASK_ID = w.TASK_ID "
                            + "LEFT JOIN EMPLOYEE_GROUP_MEMBER m ON m.GROUP_ID = a.WORK_GROUP_ID AND m.EMP_ID = e.EMP_ID "
                            + "where 1=1 ").addWhereIn("w.TASK_ID", fields).orderBy("order by w.MAKE_TIME asc");
        }
        array = query(sqlBuilder);
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            String taskId = json.getString("taskId");
            ((JSONArray) map.get(taskId)).add(json);
        }
        return map;
    }

    /**
     * 查询维修任务的附件
     * 
     * @param reqBean
     * @return
     */
    public JSONArray fileList(ReqBean reqBean) {
        String taskId = reqBean.getInfo("taskId");
        String fileSql = "SELECT * FROM MAINTENANCE_FILE f where f.TASK_ID = ?";
        return query(fileSql, taskId);
    }

    /**
     * 当申请的所有任务都完成的情况下，完成维修申请
     * 
     * @param maintenanceId
     */
    public void completeApply(String maintenanceId) {
        if (StringUtil.isEmpty(maintenanceId)) {
            throw new BusinessException("非法请求!");
        }

        MaintenanceApply apply = maintenanceApplyMapper.selectByPrimaryKey(maintenanceId);
        apply.setStatus(BusConstant.MaintenanceApply.APPLY_STATUS_COMPLETE);
        apply.setModifyTime(new Date());
        apply.setOperator(GlobalInput.getCurrentUserId());
        maintenanceApplyMapper.updateByPrimaryKey(apply);
    }

    /**
     * 维修进度
     * 
     * @param reqBean
     * @return
     */
    public JSONObject scheduleQuery(ReqBean reqBean) {

        String sql = "SELECT m.*,(SELECT e.EMP_NAME FROM EMPLOYEE e where e.EMP_ID = m.REPAIR_EMP_ID) repairEmpName, "
                + "b.BUS_TYPE,b.STOP_PLACE,t.WORK_GROUP_ID,g.GROUP_NAME FROM MAINTENANCE_APPLY m "
                + "LEFT JOIN MEDIA_BUS b ON b.BUS_ID = m.MEDIA_ID "
                + "LEFT JOIN MAINTENANCE_TASK t ON t.MAINTENANCE_ID = m.MAINTENANCE_ID AND t.C_TASK_TYPE = ? "
                + "LEFT JOIN EMPLOYEE_GROUP g ON g.GROUP_ID = t.WORK_GROUP_ID where m.`STATUS` <> ? ";
        SqlBuilder sqlBuilder = new SqlBuilder(sql, BusConstant.TaskType.TASK_TYPE_REPAIR,
                BusConstant.MaintenanceApply.APPLY_STATUS_COMPLETE);
        sqlBuilder.addWhere("m.COMPANY_NAME", reqBean.getInfo("companyName"));
        sqlBuilder.addWhere("m.VEHICLE_NO", reqBean.getInfo("vehicleNo"));
        sqlBuilder.addWhere("m.PLATE_NO", reqBean.getInfo("plateNo"));
        sqlBuilder.addWhere("m.LINE_NO", reqBean.getInfo("lineNo"));
        sqlBuilder.addWhereLike2("m.AD_NAME", reqBean.getInfo("adName"));

        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 任务待办
     * 
     * @param reqBean
     * @return
     */
    @FieldAlias(service = "maintenanceApplyService", field = "taskId", alias = "taskDetails", param = BusConstant.MaintenanceApply.APPLY_QUERY_TASK_DETAILS)
    public JSONObject mtQuery(ReqBean reqBean) {
        String sql = "select a.*,g.GROUP_NAME,m.C_LEADER_FLAG,e.EMP_NAME from MAINTENANCE_TASK a "
                + "LEFT JOIN EMPLOYEE e ON e.EMP_ID = a.`OWNER` "
                + "LEFT JOIN EMPLOYEE_GROUP g ON g.GROUP_ID = a.WORK_GROUP_ID "
                + "LEFT JOIN EMPLOYEE_GROUP_MEMBER m ON a.WORK_GROUP_ID = m.GROUP_ID AND m.EMP_ID = "
                + "(SELECT u.SOURCE_ID FROM SYS_USER u where u.USER_ID = '" + reqBean.getUserId() + "') "
                + "where EXISTS (SELECT e.*,g.GROUP_ID FROM SYS_USER u "
                + "LEFT JOIN EMPLOYEE e ON e.EMP_ID = u.SOURCE_ID "
                + "LEFT JOIN EMPLOYEE_GROUP_MEMBER g ON g.EMP_ID = e.EMP_ID "
                + "where g.GROUP_ID = a.WORK_GROUP_ID AND u.USER_ID = '" + reqBean.getUserId() + "') "
                + "OR a.`OWNER` = (SELECT su.SOURCE_ID FROM SYS_USER su where su.USER_ID = '" + reqBean.getUserId()
                + "')";
        SqlBuilder sqlBuilder = new SqlBuilder(sql);
        sqlBuilder.addWhereLike2("a.MAINTENANCE_ID", reqBean.getInfo("maintenanceId"));
        sqlBuilder.addWhere("a.C_TASK_TYPE", reqBean.getInfo("taskType"));
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 任务完成
     * 
     * @param reqBean
     */
    public void mtComplete(ReqBean reqBean) {

        String taskId = reqBean.getInfo("taskId");
        String empListStr = reqBean.getInfo("empList");
        String repairEmpId = reqBean.getInfo("repairEmpId");
        boolean hasOwnerFlag = Boolean.parseBoolean(reqBean.getInfo("hasOwnerFlag"));
        String filesStr = reqBean.getInfo("files");
        if (StringUtil.isEmpty(taskId)) {
            throw new BusinessException("非法请求!");
        }

        // 更改任务信息
        MaintenanceTask task = maintenanceTaskMapper.selectByPrimaryKey(taskId);
        task.setStatus(BusConstant.Task.STATUS_COMPLETE);
        task.setEndTime(new Date());
        task.setModifyTime(new Date());
        task.setComment(reqBean.getInfo("comment"));
        maintenanceTaskMapper.updateByPrimaryKey(task);

        MaintenanceApply maintenanceApply = maintenanceApplyMapper.selectByPrimaryKey(task.getMaintenanceId());

        if (hasOwnerFlag) { // 有办理人
            MaintenanceWorker ownerWorker = new MaintenanceWorker();
            ownerWorker.setEmpId(task.getOwner());
            ownerWorker.setTaskId(taskId);
            ownerWorker.setMakeTime(new Date());
            ownerWorker.setModifyTime(new Date());
            ownerWorker.setOperator(reqBean.getUserId());
            maintenanceWorkerMapper.insert(ownerWorker);

            if (BusConstant.TaskType.TASK_TYPE_CAITU.equals(task.getTaskType())) { // 裁图任务
                maintenanceApply.setCaituEmpId(task.getOwner());
                maintenanceApply.setCaituTime(new Date());
                maintenanceApply.setOperator(reqBean.getUserId());
                maintenanceApply.setModifyTime(new Date());
            } else if (BusConstant.TaskType.TASK_TYPE_PRINT.equals(task.getTaskType())) { // 打印任务
                maintenanceApply.setPrintEmpId(task.getOwner());
                maintenanceApply.setPrintTime(new Date());
                maintenanceApply.setOperator(reqBean.getUserId());
                maintenanceApply.setModifyTime(new Date());
            } else if (BusConstant.TaskType.TASK_TYPE_FUMO.equals(task.getTaskType())) { // 按照覆膜任务完成胶贴时间修改
                maintenanceApply.setFumoEmpId(task.getOwner());
                maintenanceApply.setFumoTime(new Date());
                maintenanceApply.setOperator(reqBean.getUserId());
                maintenanceApply.setModifyTime(new Date());
                maintenanceApply.setStickerTime(new Date());
            }
            maintenanceApplyMapper.updateByPrimaryKey(maintenanceApply);
        } else { // 工作组
            if (StringUtil.isEmpty(empListStr) || "[]".equals(empListStr)) {
                throw new BusinessException("非法请求!");
            }

            // 插入申请单的修补画师
            if (!StringUtil.isEmpty(repairEmpId)) { // 修补画师字段不为空的时候
                maintenanceApply.setRepairEmpId(repairEmpId);
            } else {
                // 插入修补时间
                maintenanceApply.setRepairTime(new Date());
                maintenanceApply.setModifyTime(new Date());
                maintenanceApply.setOperator(reqBean.getUserId());
            }
            maintenanceApplyMapper.updateByPrimaryKey(maintenanceApply);

            // 插入办理人
            JSONArray empList = JSONArray.fromObject(empListStr);
            for (int i = 0; i < empList.size(); i++) {
                JSONObject json = empList.getJSONObject(i);
                MaintenanceWorker work = new MaintenanceWorker();
                work.setTaskId(taskId);
                work.setEmpId(json.getString("empId"));
                work.setMakeTime(new Date());
                work.setModifyTime(new Date());
                work.setOperator(reqBean.getUserId());
                maintenanceWorkerMapper.insert(work);
            }

            // 处理附件
            JSONArray fileList = JSONArray.fromObject(filesStr);
            if (fileList != null && fileList.size() > 0) {
                for (int i = 0; i < fileList.size(); i++) {
                    JSONObject fileJson = fileList.getJSONObject(i);
                    MaintenanceFile file = new MaintenanceFile();
                    file.setTaskId(task.getTaskId());
                    file.setFileId(intIncrementId("MAINTENANCE_FILE", "FILE_ID"));
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setMakeTime(new Date());
                    file.setModifyTime(new Date());
                    file.setOperator(reqBean.getUserId());
                    maintenanceFileMapper.insert(file);
                }
            }
        }

    }

    /**
     * 提供生成二维码的加密字符串
     * @param reqBean
     */
    public JSONObject appCreateCode(ReqBean reqBean) {
        String maintenanceId = reqBean.getInfo("maintenanceId");
        if(StringUtil.isEmpty(maintenanceId)) {
            throw new BusinessException("非法请求!");
        }

        Date nowDate = new Date();

        // 当前时间戳
        String encryptDate = String.valueOf(nowDate.getTime());

        String maintenanceStr = null;
        String tempStr = "{ 'maintenanceId' : '" + maintenanceId + "', 'encryptDate' : '" + encryptDate + "'}";
        JSONObject returnJson = new JSONObject();
        try {
            DesUtils desUtils = new DesUtils();
            maintenanceStr = desUtils.encrypt(tempStr);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseError("加密异常");
        }
        returnJson.put("maintenanceStr", maintenanceStr);
        return Response.responseSuccess(returnJson);
    }

}